<?php
/**
 * DMFramework
 * 
 * @license Copyright 2012 Dillen Meijboom under the Apache license version 2.0 (http://apache.org/licenses/LICENSE-2.0)
 * @author Dillen Meijboom <info@dillenm.nl>
 * @url http://dmframework.nl
 */

/**
 * The translation class can be used to translate files.
 * 
 * @license Copyright 2012 Dillen Meijboom under the Apache license version 2.0 (http://apache.org/licenses/LICENSE-2.0)
 * @author Dillen Meijboom <info@dillenm.nl>
 * @package System.Library
 */
class Dmf_Translation
{
    /**
     * The current language
     * 
     * @var string 
     */
    private $_current;
    
    /**
     * All translation objects
     * 
     * @var array
     */
    private $_translations;
    
    /**
     * Translation instances
     * 
     * @var array 
     */
    private $_instances;
    
    /**
     * Constructor
     * 
     * @param string $name 
     */
    public function __construct( $name = 'lang' )
    {
        $this->_instances[ $name ] = $this;
    }
    
    /**
     * Get translation instance
     * 
     * @return null|Dmf_Translation
     */
    public function getInstance( $name = 'lang' )
    {
        return ( isset( $this->_instances[ $name ] ) ? $this->_instances[ $name ] : null );
    }
    
    /**
     * Set current language
     * 
     * @param string $lang 
     */
    public function setLang( $lang )
    {
        $this->_current = $lang;
    }
    
    /**
     * Translate an item
     * 
     * @param string $index
     * @return string 
     */
    public function translate( $index )
    {
        $args = func_get_args();
        
        unset( $args['0'] );
        $args = array_values( $args );
        
        $item = $this->_translations[ $this->_current ]->get( $index );
        
        preg_match_all( '/%_(.*?)_%/', $item, $lang_items );
        
        foreach( $lang_items['1'] as $lang_item )
        {
            $item = str_replace( '%_' . $lang_item . '_%', $this->_translations[ $this->_current ]->get( $lang_item ), $item );
        }
        
        for ( $i = 0; $i < count( $args ); $i++ )
        {
            $item = str_replace( '%' . ( $i + 1 ), $args[ $i ], $item );
        }
        
        return $item;
    }
    
    /**
     * Add a language object
     * 
     * @param string $lang
     * @return Dmf_Translation_Lang 
     */
    public function addLanguage( $lang )
    {
        $lng = ( is_object( $lang ) ) ? $lang : new Dmf_Translation_Lang( $lang );
        
        $this->_translations[ $lang ] = $lng;
        
        return $lng;
    }
}